package com.hjx.windowtool.tablemodel;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import com.hjx.windowtool.bk.dibaqu.server.BookInfo;
import com.hjx.windowtool.util.StrUtil;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper=false)
public class TableModel extends AbstractTableModel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private List<Object> list=new ArrayList<>();
	private String[] propertys=new String[] {};
	private String[] columnNames=new String[] {};
	private long totalSize=0;
	private Class<?> clz;
	public TableModel() {}
	public TableModel(String[] propertys, String[] columnNames) {
		this(propertys, columnNames, null);
	}
	public TableModel(String[] propertys, String[] columnNames,Class<?> clz) {
		this.propertys = propertys;
		this.columnNames = columnNames;
	}
	@Override
	public int getRowCount() {
		return list.size();
	}

	@Override
	public int getColumnCount() {
		return Math.min(propertys.length, columnNames.length);
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		if("index".equals(propertys[columnIndex])) {
			return rowIndex;
		}
		Object object = list.get(rowIndex);
		return StrUtil.getFieldValueByName(propertys[columnIndex], object);
	}
	@Override
	public String getColumnName(int column) {
		return columnNames[column];
	}
	@Override
	public Class<?> getColumnClass(int columnIndex) {
		if(clz!=null) {
			try {
				Field field = clz.getField(propertys[columnIndex]);
				System.out.println(field.getType());
				return field.getType();
			} catch (NoSuchFieldException | SecurityException e) {
				e.printStackTrace();
			}
		}
		return super.getColumnClass(columnIndex);
	}
	public void setList(List<?> list) {
		this.list=new ArrayList<>(list);
		fireTableDataChanged();
	}
	public void addList(List<?> list) {
		this.list.addAll(new ArrayList<>(list));
		fireTableDataChanged();
	}
	public void addList(Object bookInfo) {
		this.list.add(bookInfo);
		fireTableDataChanged();
	}
	
}
